package com.example.ggpicturegg.bottom;

import androidx.appcompat.app.AppCompatActivity;
import com.example.ggpicturegg.R;
import android.os.Bundle;


import androidx.appcompat.app.AppCompatActivity;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.ggpicturegg.tool.MyUtils;
import com.zhangke.websocket.SimpleListener;
import com.zhangke.websocket.SocketListener;
import com.zhangke.websocket.WebSocketHandler;
import com.zhangke.websocket.response.ErrorResponse;

import java.nio.ByteBuffer;
import java.util.HashMap;

public class Talk_M_Activity extends AppCompatActivity {

    private String edt_username;
    private EditText edt_content;
    private TextView tvMsg;
    private ScrollView scrollView;
    private Button btn_send;
    private ImageView Talk_btn_return;

    private String Send_name;    //发送的名字 自己的名字
    private String R_name;      // 接受的名字 ，发送给别人的那个名字


    private SocketListener socketListener = new SimpleListener() {
        // 回调：连接成功
        @Override
        public void onConnected() {
            appendMsgDisplay("onConnected");
        }

        // 回调：连接失败
        @Override
        public void onConnectFailed(Throwable e) {
            if (e != null) {
                appendMsgDisplay("onConnectFailed:" + e.toString());
            } else {
                appendMsgDisplay("onConnectFailed:null");
            }
        }

        // 回调：断开连接
        @Override
        public void onDisconnect() {
            appendMsgDisplay("onDisconnect");
        }

        // 回调：数据发送失败
        @Override
        public void onSendDataError(ErrorResponse errorResponse) {
            appendMsgDisplay("onSendDataError:" + errorResponse.toString());
            errorResponse.release();
        }

        // 回调：接收到文本数据
        @Override
        public <T> void onMessage(String message, T data) {
            Log.d("Output", "接收长度: " + message.length());

            // 把接收到的字符串转化为HashMap<String,String>
            HashMap<String, String> hm_data = MyUtils.jstr2hm(message);
            String username = hm_data.get("username");
            String type = hm_data.get("type");
            String content = hm_data.get("content");



            if (!(type == null || type.isEmpty()) && type.equals("text")) {
                if(username.equals(Send_name)||username.equals(R_name))
                appendMsgDisplay(username + "说:" + content);
            }
        }

        // 回调：接收到二进制数据
        @Override
        public <T> void onMessage(ByteBuffer bytes, T data) {
            appendMsgDisplay("onMessage(String, T):" + bytes);
        }
    };



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_talk_mactivity);

        initView();

        WebSocketHandler.getDefault().addListener(socketListener);

    }

    private void initView() {
        edt_content = (EditText) findViewById(R.id.edt_content);
        tvMsg = (TextView) findViewById(R.id.tv_msg);
        scrollView = (ScrollView) findViewById(R.id.scroll_view);
        btn_send = (Button) findViewById(R.id.btn_send);
        Talk_btn_return = findViewById(R.id.talk_btn_return);

        Bundle bundle = getIntent().getExtras();
        Send_name = bundle.getString("Send_name");
        R_name = bundle.getString("Rend_name");

        System.out.println("Send_uname  :"+Send_name+"------------"+"R_uname  :"+R_name);

        Talk_btn_return.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        // 发送字符串数据
        btn_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取用户名
                String username = Send_name;

                // 获取发言内容
                String content = edt_content.getText().toString();
                if (TextUtils.isEmpty(content)) {
                    Toast.makeText(Talk_M_Activity.this, "输入不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }

                //把所有待传送的数据放入HashMap
                HashMap<String,String> hm_data = new HashMap<String,String>();
                hm_data.put("username",username);
                hm_data.put("type","text");
                hm_data.put("content",content);

                // 把HashMap转化为字符串
                String str_data = MyUtils.object2JsonString(hm_data);

                // 放送数据
                Log.d("Output","发送长度："+str_data.length());
                WebSocketHandler.getDefault().send(str_data);
            }
        });


        // 清空聊天文本
        findViewById(R.id.btn_clear).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvMsg.setText("");
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        WebSocketHandler.getDefault().removeListener(socketListener);
    }

    private void appendMsgDisplay(String msg) {
        StringBuilder textBuilder = new StringBuilder();
        if (!TextUtils.isEmpty(tvMsg.getText())) {
            textBuilder.append(tvMsg.getText().toString());
            textBuilder.append("\n");
        }
        textBuilder.append(msg);
        textBuilder.append("\n");
        tvMsg.setText(textBuilder.toString());
        tvMsg.post(new Runnable() {
            @Override
            public void run() {
                scrollView.fullScroll(ScrollView.FOCUS_DOWN);
            }
        });
    }
}
